﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TMT_CMS.BL.Model;

namespace TMT_CMS.BL.Utility
{
    public static class DBUtility
    {
        public static PaggingResultModel<T1,T2> BuildPaggingResult<T1,T2>(IQueryable<T1> query, PaggingRequestModel paggingModel,T2 searchCondtion)
        {
            var result = new PaggingResultModel<T1,T2>();
            result.SearchCondition = searchCondtion;

            // set total page count and current page index
            result.TotalItemCount = query.Count();
            result.TotalPageCount = (int)Math.Ceiling((double)result.TotalItemCount / (double)paggingModel.CountPerPage);
            if (result.TotalPageCount == 0)
            {
                return result;
            }

            if (paggingModel.PageIndex <= result.TotalPageCount)
            {
                result.CurrentPageIndex = paggingModel.PageIndex;
            }
            else
            {
                result.CurrentPageIndex = result.TotalPageCount;
            }

            // get entity list
            int startIndex = result.CurrentPageIndex * paggingModel.CountPerPage;
            result.StartItemIndex = startIndex + 1;
            result.ResultList = query.Skip(startIndex).Take(paggingModel.CountPerPage).ToList();
            return result;
        }
    }
}
